package top.porchwood.jweb.mcsm.controller;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;


@Controller
public class UploadFileController {
    private static final Logger logger = LogManager.getLogger();
    @PostMapping("/uploadFile/FileHandler")
    public void onFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        if(file == null || file.isEmpty()) {
            response.setStatus(500);
            try {
                var stream = response.getOutputStream();
                stream.print("{\"status\":\"NotEmpty!\"");
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        //ArrayList<Byte> bytes = new ArrayList<>();
        try {
            logger.info("%s %s %s %s".formatted(
                    file.getContentType(),
                    file.getName(),
                    String.valueOf(file.getSize()),
                    file.getOriginalFilename()
            ));
            var stream =  file.getInputStream();
            byte[] buff = new byte[1024];
            int rc = 0;
            while ((rc = stream.read(buff, 0, 1024)) > 0) {
                logger.info(Arrays.toString(buff));
                //bytes.addAll(Arrays.asList(ArrayUtils.toObject(Arrays.copyOfRange(buff, 0, rc))));
            }
            //logger.info(bytes.size());
        } catch (IOException e) {
            logger.error(e);
            response.setStatus(500);
        }
        //if(file.getContentType().startsWith("text")){
        //    logger.info(new String(ArrayUtils.toPrimitive(bytes.toArray(Byte[]::new))));
        //}
        response.setStatus(200);
        try {
            var os = response.getOutputStream();
            os.print("{\"status\":\"ok\"}");
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
